<?php

namespace Tasker\Models;

class TaskModel extends BaseModel
{

	private $id;

	public function find($id)
	{
		$this->id = $id;
		return $this;
	}

	public function getTask()
	{
		return $this->connection->task[$this->id];
	}

	public function getHistory()
	{
		$status = $this->connection->task_status_history->select("date, user_id, task_status_id, null as completed, 'status' as type")->where('task_id', $this->id);
		$completed = $this->connection->task_completed_history->select("date, user_id, null as task_status_id, completed, 'completed' as type")->where('task_id', $this->id);
		return $status->union($completed)->order('date desc');
	}

	public function getPrerequisites()
	{
		return $this->connection->prerequisite_task()->where('task_id', $this->id);
	}

	public function getPreconditionFor()
	{
		return $this->connection->prerequisite_task()->where('prerequisite_id', $this->id);
	}

	public function getComments()
	{
		return $this->connection->task_comment()->where('task_id',  $this->id)->order('date asc');
	}
	
	public function setStatus($status, $user)
	{
		if($this->getTask()->update(array('task_status_id' => $status)) !== false)
		{
			$this->connection->task_status_history()->insert(array('task_id'=>$this->id,'user_id'=>$user,'task_status_id'=>$status,'date'=>new \DateTime));
			return true;
		}
		return false;
	}
	
	public function setCompleted($completed, $user)
	{
		if($this->getTask()->update(array('completed' => $completed)) !== false)
		{
			$this->connection->task_completed_history()->insert(array('task_id'=>$this->id,'user_id'=>$user,'completed'=>$completed,'date'=>new \DateTime));
			return true;
		}
		return false;
	}
}
